<template>
  <view class="policy-container screen-width">
    <topBar :title="`政策订阅`" />
    <view class="searchBar flex">
      <view class="search">
        <input type="text" placeholder="请输入你要订阅的部门或地区" v-model="getKeyword" />
        <image src="../../static/policy/search.png" mode @tap="changeSearch" />
      </view>
    </view>
    <view class="selectBar">
      <span>
        <input type="text" :value="address ? address : '地区'" @tap="showArea" disabled />
        <image src="../../static/proty/botton_icon.png" mode />
      </span>
      <view @click="toCurrent" style="color: #1678ff;background: #fff;padding: 10upx;">切换当前定位</view>
      <view class="area_R">共为您找到{{ total}}个部门</view>
    </view>

    <!-- 搜索结果 -->
    <view class="depart-content">
      <!-- 省部门 -->
      <view class="list-content">
        <view class="area-name flex items-middle">
          {{areaSubscriptList[0].name || '--'}}
        </view>
        <view v-if="areaSubscriptList[0].childs.length" class="list-item-box flex flex-wrap items-middle">
          <view v-for="(item,index) in areaSubscriptList[0].childs" :key="index" class="list-item-row">
            <view class="list-item border-bottom items-middle flex items-middle space-between">
              <view class="name multipleRow text-black">{{item.departmentName}}</view>
              <text
                class="btn"
                v-if="item.whetherAttention ==0"
                @tap="isSubscription(item.whetherAttention,item.id, dataItem.city ? 2:1)"
              >订阅</text>
              <text
                class="btn"
                v-else
                @tap="isSubscription(item.whetherAttention,item.id, dataItem.city ? 2:1)"
              >已订阅</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 市部门 -->
      <view v-if="dataItem.province !='' && dataItem.province != '国家'">
        <view v-if="areaSubscriptList[0].departments.length>1">
          <view v-for="(item,index) in areaSubscriptList[0].departments" :key="index" class="list-content">
            <view class="area-name flex items-middle">
              {{item.name || '--'}}
            </view>
            <view v-if="item.childs.length" class="list-item-box flex flex-wrap items-middle">
              <view v-for="(v,k) in item.childs" :key="k" class="list-item-row">
                <view class="list-item border-bottom items-middle flex items-middle space-between">
                  <view
                    class="multipleRow name text-black"
                  >{{v.departmentName || '--'}}</view>
                  <text
                    class="btn"
                    v-if="v.whetherAttention ==0"
                    @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
                  >订阅</text>
                  <text
                    class="btn"
                    v-else
                    @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
                  >已订阅</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-else>
          <view class="list-content">
            <view class="area-name flex items-middle">
              {{areaSubscriptList[0].departments[0].name || '--'}}
            </view>
            <view v-if="areaSubscriptList[0].departments[0].childs.length" class="list-item-box flex flex-wrap items-middle">
              <view
                v-for="(item,index) in areaSubscriptList[0].departments[0].childs"
                :key="index"
                class="list-item-row"
              >
                <view class="list-item border-bottom items-middle flex items-middle space-between">
                  <view
                    class="multipleRow name text-black"
                  >{{item.departmentName || '--'}}</view>
                  <text
                    class="btn"
                    v-if="item.whetherAttention ==0"
                    @tap="isSubscription(item.whetherAttention,item.id, dataItem.city ? 2:1)"
                  >订阅</text>
                  <text
                    class="btn"
                    v-else
                    @tap="isSubscription(item.whetherAttention,item.id, dataItem.city ? 2:1)"
                  >已订阅</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 区部门 -->
      <view v-if="dataItem.city !='' && dataItem.province != '国家'">
        <view v-if="areaSubscriptList[0].departments[0].departments.length">
          <view
            v-for="(item,index) in areaSubscriptList[0].departments[0].departments"
            :key="index"
            class="list-content"
          >
            <view class="area-name flex items-middle">
              {{item.name || '--'}}
            </view>
            <view class="list-item-box flex flex-wrap items-middle">
              <view v-for="(v,k) in item.childs" :key="k" class="list-item-row">
                <view class="list-item border-bottom items-middle flex items-middle space-between">
                  <view
                    class="multipleRow name text-black"
                  >{{v.departmentName || '--'}}</view>
                  <text
                    class="btn"
                    v-if="v.whetherAttention ==0"
                    @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
                  >订阅</text>
                  <text
                    class="btn"
                    v-else
                    @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
                  >已订阅</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>   
    <view class="noData" v-show="areaSubscriptList.length== 0 ">
      <text>没有更多了</text>
    </view>
    <!-- 地区 -->
    <PickerView
      ref="picker"
      :isshowArea="isshowArea"
      :type="proType"
      @affirm="affirm"
      @cancel="cancel"
    ></PickerView>
    <!-- 订阅部门选取关键字 -->
    <keyWord ref="keyword" @onSubmit="attention"></keyWord>
    <Festival></Festival>
  </view>
</template>

<script>
import topBar from "../../components/topBar.vue";
import dialoguse from "../../components/dialog.vue";
import { isWeixin, wxShareConfig } from "util/wx.js";
import {
  departmentAttention,
  cancelAttention,
  getPolicyDepartmentSubscribeInfo
} from "../../util/api/policy.js";
export default {
  components: {
    topBar,
    dialoguse
  },
  data() {
    return {
      itemCity: "",
      itemArea: "",
      showToast: {
        msg: "请先登陆后,在操作",
        affirm: "马上登录"
      },
      isSearch: false, // 搜索状态
      show: false, // 是否显示登陆框
      isshowArea: false, // 是否显示地区
      areaList: {}, // 获取地区列表
      address: "", // 展示的地区
      dataItem: {
        province: "", // 省份
        city: "", // 城市
        area: "" //地区
      },
      getKeyword: "", // 关键字
      SubscriptionData: [], // 订阅列表数据(随机订阅列表)
      areaSubscriptList: [], // 地区订阅
      total: 0, // 获取政策订阅的条数

      valueArr: [0, 0, 0], // 用于判断当前滑动的是哪一列
      proType: 2,
      nProvince: "",
      nCity: "",

      latitude: "",
      longitude: ""
    };
  },
  onShow() {
    this.address = uni.getStorageSync("city");
    this.getSub();
  },
  onHide() {
    this.nProvince = "";
    this.nCity = "";
  },
  methods: {
    // 切换当前定位
    toCurrent() {
      this.address = "";
      this.init();
    },
    // 点击下一项
    selectAreaItem(val) {
      // console.log(val);
      uni.pageScrollTo({
        // 回到顶部
        scrollTop: 0,
        duration: 0
      });
    },
    isLogin(val) {
      if (val == false) {
        this.show = false;
      }
    },
    // 订阅
    isSubscription(isAttention, id, type, pIndex) {
      let token = this.$getToken();
      if (!token) {
        uni.showModal({
          title: "提示",
          content: "请先登录后,在操作",
          confirmText: "马上登录",
          success(res) {
            if (res.confirm) {
              uni.setStorageSync("pageUrl", window.location.href);
              uni.navigateTo({
                url: "/pages/login/index"
              });
            }
          }
        });
        return;
      }
      if (isAttention === 0) {
        this.$refs.keyword.open(id);
      } else {
        let _this = this;
        uni.showModal({
          title: "提示",
          content: "您确定要取消订阅吗,取消后将不再接收该部门的政策推送",
          confirmText: "确定",
          success(res) {
            if (res.confirm) {
              cancelAttention(id).then(res => {
                if (res.code === 200) {
                  uni.showToast({ title: "操作成功", icon: "none" });
                  _this.getSubscriptionList();
                } else {
                  uni.showToast({ title: res.message });
                }
              });
            }
          }
        });
      }
    },
    attention(id, keyWord) {
      let params = {
        departmentId: id,
        keywords: keyWord
      };
      departmentAttention(params).then(res => {
        if (res.code === 10002) {
          uni.showModal({
            title: "提示",
            content: res.message,
            confirmText: "升级会员",
            success: function(res) {
              if (res.confirm) {
                uni.navigateTo({
                  url: "/pages/VIP/index"
                });
              }
            }
          });
        } else if (res.code === 200) {
          uni.showToast({ title: "关注成功", icon: "none" });
          this.getSubscriptionList();
        }
      });
    },
    // 选择地区的(显示地区框)
    showArea() {
      this.isshowArea = true;
    },
    // 选择地区的退出按钮
    cancel() {
      this.isshowArea = false;
    },
    // 点击换一批
    next() {
      this.getrandomList();
    },
    // 获取经纬度，腾讯地图接口解析
    init() {
      var that = this;
      uni.getLocation({
        type: "gcj02",
        geocode: true,
        success: res => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          // 解析地址
          this.handleLocation();
        },
        fail: err => {
          this.init();
        }
      });
    },
    handleLocation() {
      let location = this.latitude + "," + this.longitude;
      this.$get("/bmj-api/api/tencent/getLocation", {
        location: location
      }).then(res => {
        this.$nextTick(function() {
          this.dataItem.province = ""; // 省
          this.dataItem.city = res.result.ad_info.city; // 市
          this.getSubscriptionList();
        });
      });
    },
    // 获取订阅列表
    getSub() {
      if (!this.nProvince && !this.nCity) {
        let city = uni.getStorageSync("city");
        let province = uni.getStorageSync("province");
        if (city && province) {
          this.dataItem.city = city;
          this.dataItem.province = province;
          this.getSubscriptionList();
        } else {
          this.init();
        }
      }
      if (isWeixin()) {
        this.initShareConfig();
      }
    },
    getSubscriptionList() {
      let obj = {
        province: this.dataItem.province, // 省份
        city: this.dataItem.city, // 城市
        area: this.dataItem.area, // 地区
        departmentName: this.getKeyword, // 关键字
      };
      for (let key in obj) {
        if (!String(obj[key]).length) {
          delete obj[key];
        }
      }
      // 选择地区后数据列表的请求
      getPolicyDepartmentSubscribeInfo(obj).then(res => {
        if (res.code == 200) {
          let { departmentTotal } = res.result;
          this.total = departmentTotal;
          this.areaSubscriptList = res.result.departmentInfo
          console.log(99999999,this.areaSubscriptList[0].name)
        }
      });
    },
    // 点击确定按钮
    affirm(province, city, area) {
      this.dataItem.province = province;
      this.dataItem.city = city;
      this.dataItem.area = area;
      let arr = [];
      if (this.dataItem.province) {
        arr.push(this.dataItem.province);
      }
      if (this.dataItem.province && this.dataItem.city) {
        arr.push(this.dataItem.province);
        arr.push(this.dataItem.city);
      }
      if (this.dataItem.province && this.dataItem.city && this.dataItem.area) {
        arr.push(this.dataItem.province);
        arr.push(this.dataItem.city);
        arr.push(this.dataItem.area);
      }
      let arrLen = Array.from(new Set(arr));

      for (let i = 0; i < arrLen.length; i++) {
        if (arrLen[i] === "请选择") {
          arrLen.splice(i, 1);
        }
      }
      this.isSearch = true;

      if (arrLen.length === 1) {
        this.dataItem.area = "";
        this.dataItem.city = "";
        this.dataItem.province = arrLen[0];
        this.getSubscriptionList();
      } else if (arrLen.length === 2) {
        this.dataItem.province = arrLen[0];
        this.dataItem.area = "";
        this.dataItem.city = arrLen[1];
        this.getSubscriptionList();
      } else if (arrLen.length === 3) {
        this.dataItem.province = arrLen[0];
        this.dataItem.city = arrLen[1];
        this.dataItem.area = arrLen[2];
        this.getSubscriptionList();
      } else {
        this.address = "";
        this.getrandomList();
        // 点击退出按钮
        this.cancel();
        return;
      }
      this.address = arrLen.pop();
      this.nProvince = this.dataItem.province;
      this.nCity = this.dataItem.city;
      // 点击退出按钮
      this.cancel();
    },
    // 点击搜索内容
    changeSearch() {
      if (!this.getKeyword && !this.address) {
        this.isSearch = false;
        uni.showToast({
          title: "请输入你要查询的部门或地区",
          duration: 2000,
          icon: "none"
        });
        return;
      }
      this.isSearch = true;
      this.getSubscriptionList();
    },

    // 随机获取订阅列表
    getrandomList() {
      this.$get("/bmj-api/api/pms/pmsDepartment/randomObtainDepartment").then(
        res => {
          if (res.code == 200) {
            this.total = res.result.length;
            this.SubscriptionData = res.result;
          }
        }
      );
    },
    // 政策部门通知
    toDepartPolicy(id) {
      uni.navigateTo({
        url: `/pages/policy/departPolicy?id=${id}`
      });
    },

    initShareConfig() {
      let _this = this;
      let windowurl = window.location.href.split("#")[0];
      uni.request({
        url: "https://oldm.51bmj.cn/WeiXin/GetClientSign", //仅为示例，并非真实接口地址。
        data: {
          rawUrl: windowurl
        },
        dataType: "json",
        header: {
          "X-Requested-With": "XMLHttpRequest"
        },
        method: "GET",
        success: res => {
          if (res.statusCode == 200) {
            let { data } = res;
            let shareInfo = {
              title: "政策订阅",
              desc: "最新政策一键订阅，实时推送",
              link: window.location.href
            };
            wxShareConfig(this.$wx, data, shareInfo);
          }
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.policy-container{
  .searchBar {
    height: 120rpx;
    padding: 20rpx 30rpx;
    background-color: #fff;

    .search {
      height: 80rpx;

      display: flex;
      border-radius: 15rpx;
      align-items: center;
      background-color: #f8f8f8;
      justify-content: space-around;
      padding-left: 20rpx;

      input {
        flex: 1;

        &::placeholder {
          font-size: 14px;
        }
      }

      image {
        width: 32rpx;
        height: 32rpx;
        margin: 0 30rpx;
      }
    }
  }
  .selectBar {
    height: 120rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      width: 170rpx;
      height: 60rpx;
      background-color: #fff;
      display: flex;
      padding: 0rpx 20rpx;
      align-items: center;

      image {
        width: 14rpx;
        height: 10rpx;
      }

      input {
        width: 100rpx;
        font-size: 14px;
        color: #44a2ff;
      }
    }

    .area_R {
      color: #ffaa8d;
      font-size: 13px;
    }
  }
  .depart-content{
    background: #f8f9fd;
    padding: 30rpx;
    box-sizing: border-box;
    .area-name{
      font-size: 30rpx;
      color: #333333;
      font-weight: bold;
      margin-top: 20rpx;
    }
    .list-item-box{
      background: #ffffff;
      width: 100%;
      padding: 10rpx 10rpx 40rpx 10rpx;
      margin-top: 20rpx;
      .list-item-row{
        // width: 48%;
        width: 50%;
        padding-right: 20rpx;
        .list-item{
          margin-top: 30rpx;
          .name{
            flex: 1;
            font-size: 12px;
          }
          .btn {
            width: 80rpx;
            height: 40rpx;
            line-height: 40rpx;
            text-align: center;
            background-color: #1678ff;
            margin-left: 20rpx;
            font-size: 12px;
            border-radius: 0;
            color: #fff;
            white-space: nowrap;
          }
        }
      }
      
    }
    
  }
}
.noData {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  height: 40rpx;
  color: #aaaaaa;
  margin: 40rpx auto;
}
</style>
